package com.crpc.common.utils.NetWork;

import cn.hutool.core.util.ObjectUtil;
import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author CLOUD
 * @version 1.0
 * @description:
 * @date 2023/9/8 16:46
 */
@Slf4j
public class NetUtils {
    //内网ip
    public static String getIntranetIp() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                //过滤非回环接口和虚拟接口
                if (iface.isLoopback() || iface.isVirtual() || !iface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> address = iface.getInetAddresses();
                while (address.hasMoreElements()) {
                    InetAddress addr = address.nextElement();
                    if (addr instanceof Inet6Address || addr.isLoopbackAddress()) {
                        continue;
                    }
                    return addr.getHostAddress();
                }
            }
            throw new CrpcException(CrpcExceptionEnums.ZOOKEEPER_ERROR);
        } catch (Exception e) {
            log.error("获取ip地址失败", e);
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.ZOOKEEPER_ERROR);
        }
    }

    //公网ip
    public static String getPublicIp() {
        String url = "http://ip.42.pl/raw";
        Document document = null;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            log.error("获取ip的地址已经失效");
        }
        if (ObjectUtil.isNull(document)) {
            return "";
        }
        return document.text();
    }
}
